<template>
  <div>
    <Dropdown :trigger="trigger" :placement="placement" :visible="visible" @on-clickoutside="onClickoutside"
              :transfer="transfer">
      <div @click="onClick">
        <p v-if="showType === 'text'">{{inputVal ? inputVal : placeholder}}
          <Icon style="margin-left: 20px;" type="arrow-down-b"></Icon>
        </p>
        <i-input icon="arrow-down-b" size="large" :value="inputVal" readonly :placeholder="placeholder"
                 v-else></i-input>
      </div>
      <div slot="list" :style="{width:width,height:height}">
        <Table :columns="columns" :data="tableData" @on-row-click="onRowClick" highlight-row
               @on-selection-change="onSelectChange" @on-select="onSelect" @on-select-all="onSelectAll"
               @on-select-cancel="onSelectCancel"></Table>
      </div>
    </Dropdown>
  </div>
</template>

<script>

export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
    columns: {
      type: Array
    },
    tableData: {
      type: Array
    },
    clickOut: {
      type: Boolean,
      default: false
    },
    text: {
      type: String
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    showType: {
      type: String
    },
    width: {
      type: String,
      default: 'auto'
    },
    height: {
      type: String,
      default: 'auto'
    },
    placement: {
      type: String,
      default: 'bottom'
    },
    trigger: {
      type: String,
      default: 'custom'
    },
    transfer: {
      type: Boolean,
      default: true
    },
    clickContent: {
      type: Boolean,
      default: true
    }
  },
  data () {
    return {
      inputVal: '',
      visible: this.value
    }
  },
  watch: {
    value (val) {
      this.visible = val
    },
    visible (val) {
      this.$emit('input', val)

      if (val) {
        this.$emit('on-show')
      } else {
        this.$emit('on-hide')
      }
    }
  },
  methods: {
    onClick () {
      this.visible = this.clickContent ? !this.visible : true
    },
    onRowClick (data, index) {
      if (this.columns[0].type !== 'selection') {
        this.inputVal = data[this.text]
      }
      this.$emit('on-selected', data)
    },
    onClickoutside () {
      this.visible = this.clickOut
    },
    onSelectChange (data) {
      this.inputVal = data.length === 0 ? this.placeholder : `已选择${data.length}个`
      if (data.length === 0) {
        this.$emit('on-unselected', [], this.tableData)
      }
    },
    onSelect (data) {
      this.$emit('on-selected', data)
    },
    onSelectAll (data) {
      this.$emit('on-selected', data)
    },
    onSelectCancel (data, row) {
      this.$emit('on-unselected', data, [row])
    }
  }
}
</script>

<style>

</style>
